import axios from "axios";
import { getToken } from "@/utils/auth";
import { getEnv } from "./env.js";
import cache, {interceptorsRequest} from "./cache.js";
export { getToken }
let config = {}
if(window.BASE_URL){
  config.baseURL = window.BASE_URL
}
const request = axios.create(config);

request.interceptors.request.use(interceptorsRequest);

request.interceptors.request.use((config) => {
  // console.log('config', config)
  let token = getToken();
  config.headers["Authorization"] = token;
  return config;
});
request.interceptors.response.use((res) => {
  //请求成功
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200;
  const msg = res.data.msg;
  if (code !== 200) {
    return Promise.reject(new Error(msg));
  }
  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
    return res.data
  }
  //缓存结果到缓存中
  cache.add(res);
  return res;
});

export async function get(url, params, headers) {
  let {
    data: { data },
  } = await request.get(url, {
    params,
    headers: { Authorization: getToken(), ...headers },
  });
  return data;
}

export async function post(url, data) {
  let {
    data: { data: result },
  } = await request.post(url, data, {
    headers: { Authorization: getToken() },
  });
  return result;
}

export default request;
